package com.solution.action;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.upload.FormFile;
import com.solution.constant.LoginConstants;
import com.solution.constant.StatusConstants;
import com.solution.delegate.ExaminationServiceDelegate;
import com.solution.delegate.UserInfoServiceDelegate;
import com.solution.delegate.UserRolePermissionServiceDelgate;
import com.solution.exception.DelegateException;
import com.solution.exception.ServiceBeanException;
import com.solution.form.UserForm;
import com.solution.model.AnswerType;
import com.solution.model.CategoryType;
import com.solution.model.ExamType;
import com.solution.model.LevelType;
import com.solution.model.QuestionType;
import com.solution.model.UserInfo;
import com.solution.model.UserPermissionType;
import com.solution.model.UserRole;
import com.solution.util.SearchVO;

public class UserAction extends Action {
	Logger logger = Logger.getLogger(UserAction.class.getName());
	/**
	 * Date format.
	 */
	private static SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");

	public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		UserForm loc_o_form = (UserForm)form;
		request.setAttribute("tab", "USER");
		if("/updateUser".equals(mapping.getPath())){
			return updateUser(mapping, loc_o_form, request,response);
		}		
		if("/userSearchdetails".equals(mapping.getPath())){
			return userSearchdetail(mapping, loc_o_form,request);
		}		
		if("/searchUserResult".equals(mapping.getPath())){
			return searchUserResult(mapping, loc_o_form);
		}		
		if("/searchUserScreen".equals(mapping.getPath())){
			return searchUserScreen(mapping, loc_o_form);
		}
		if("/addUser".equals(mapping.getPath())){
			return addUser(mapping, loc_o_form,request,response);
		}
		if("/user".equals(mapping.getPath())){
			return createEditUserScreen(mapping, loc_o_form,request);
		}
		if("/isUserNameExist".equals(mapping.getPath())){
			return isUserNameExist(mapping, loc_o_form,request,response);
		}
		if("/uploadUserFileScreen".equals(mapping.getPath())){
			return mapping.findForward("uploadScreen");
		}
		if("/uploadUserFile".equals(mapping.getPath())){
			return uploadUserFile(mapping, loc_o_form, request, response);
		}
		return mapping.findForward("error");
	}
	public ActionForward uploadUserFile(ActionMapping mapping,UserForm loc_o_form,HttpServletRequest request, 
			HttpServletResponse response) throws IOException, ServletException {
		logger.debug("Entering :: UserAction:uploadUserFile()");
		ActionMessages  errors  = new ActionMessages();
		HttpSession session = request.getSession();
		UserInfo userInfo = null;
		if(session != null){
			userInfo = (UserInfo)session.getAttribute(LoginConstants.SESSION_USER_INFO);
		}
		try{
			FormFile file = loc_o_form.getBulk_users() ;
			String outputFileName = file.getFileName().substring(0,file.getFileName().length()-4)+"_Result.xls";
			InputStream xlsStream = file.getInputStream();
			HSSFWorkbook outputFile = createBasicUserFile();
			HSSFSheet outputSheet = outputFile.getSheetAt(0);
			HSSFWorkbook wb = new HSSFWorkbook(xlsStream);
			HSSFSheet sheet = wb.getSheetAt(0);
			Iterator<HSSFRow> rows = sheet.rowIterator();
			int recordCount = 0;
			int rowIndex = 1;
			rows.next();//First Line will be headers. So, skip it.
			ExaminationServiceDelegate examinationServiceDelegate = new ExaminationServiceDelegate();
			while(rows.hasNext()){
				recordCount++;
				HSSFRow row = (HSSFRow) rows.next();
				HSSFRow outputRow = outputSheet.createRow(rowIndex);
				Iterator<HSSFCell> iter = row.cellIterator();
				while(iter.hasNext()){
					HSSFCell cell = (HSSFCell) iter.next();
					if(isDateType(cell)){
						outputRow.createCell(cell.getColumnIndex()).setCellValue(new HSSFRichTextString(dateFormat.format(cell.getDateCellValue())));
					}
					else if(isNumericType(cell)){
						outputRow.createCell(cell.getColumnIndex()).setCellValue(cell.getNumericCellValue());
					}
					else if(isBooleanType(cell)){
						outputRow.createCell(cell.getColumnIndex()).setCellValue(cell.getBooleanCellValue());
					}
					else{
						outputRow.createCell(cell.getColumnIndex()).setCellValue(cell.getRichStringCellValue());
					}
				}
				createUserEntry(row, examinationServiceDelegate, userInfo,outputRow);
				rowIndex++;
			}
			File file1 = null;
			File fileTemp = null;
			DataOutputStream dos = null;
			FileOutputStream fos;
			fileTemp= new File("D:/ProductionFiles/UserUpload");
			fileTemp.mkdir();
			file1 = new File("D:/ProductionFiles/UserUpload/"+outputFileName);
			file1.createNewFile();
			fos = new FileOutputStream(file1);
			dos=new DataOutputStream(fos);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			outputFile.write(bos);
			dos.write(bos.toByteArray());
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition","attachment; filename=" +outputFileName);
			ServletOutputStream outputStream = response.getOutputStream();
			outputStream.write(bos.toByteArray());
			outputStream.flush();
			outputStream.close();
			dos.close();
			fos.close();
			return null;
		}
		catch(DelegateException de){
			logger.error(de);
			errors.add("error", new ActionMessage("User.add.fail"));
		}
		saveErrors(request, errors);
		logger.debug("Exiting :: UserAction:uploadUserFile()");
		return mapping.findForward("successUploadUserFile");
	}
	
	private void createUserEntry(HSSFRow row, ExaminationServiceDelegate examinationServiceDelegate, 
			UserInfo userInfo, HSSFRow outputRow) throws DelegateException{
		try{
			UserInfoServiceDelegate userInfoService = new UserInfoServiceDelegate();
			Iterator<HSSFCell> cells = row.cellIterator();
			HSSFCell cell;
			UserInfo userInfo1 = new UserInfo();
			userInfo1.setCreatedOn(new Date());
			userInfo1.setCreatedBy(userInfo.getUsername());
			userInfo1.setStatus(StatusConstants.ACTIVE);			
    		userInfo1.setRetryPasswordCount((byte)3);    		
    		userInfo1.setIsDefault(true);
    		userInfo1.setStatus(LoginConstants.USER_ACTIVE);
    		String password;
    		String examIDString;
    		String userTypeString;
    		
			outputRow.createCell(6).setCellValue(new HSSFRichTextString("Success"));
			while(cells.hasNext()){
				cell = (HSSFCell) cells.next();
				logger.info("The cellIndex is :"+cell.getColumnIndex());
				switch(cell.getColumnIndex()){
					case 0://First Name
						userInfo1.setFirstName(cell.getRichStringCellValue().getString().trim());
						break;
					case 1://Last Name
						userInfo1.setLastName(cell.getRichStringCellValue().getString().trim());						
						break;
					case 2://User Name
						userInfo1.setUsername(cell.getRichStringCellValue().getString().trim());
						break;
					case 3://Password						
						if(isDateType(cell)){
							password = dateFormat.format(cell.getDateCellValue());
						}
						else if(isNumericType(cell)){
							password = String.valueOf(cell.getNumericCellValue());
						}
						else if(isBooleanType(cell)){
							password = String.valueOf(cell.getBooleanCellValue());
						}
						else{
							password = cell.getRichStringCellValue().getString().trim();
						}
						userInfo1.setPassword(userInfoService.encryptPassword(password));						
						break;
					case 4://Exam ID
						if(isDateType(cell)){
							examIDString = dateFormat.format(cell.getDateCellValue());
						}
						else if(isNumericType(cell)){
							examIDString = String.valueOf(Math.round(cell.getNumericCellValue()));
						}
						else if(isBooleanType(cell)){
							examIDString = String.valueOf(cell.getBooleanCellValue());
						}
						else{
							examIDString = cell.getRichStringCellValue().getString().trim();
						}
						userInfo1.setExamTypeId(Long.parseLong(examIDString));
						break;
					case 5://User Type
						if(isDateType(cell)){
							userTypeString = dateFormat.format(cell.getDateCellValue());
						}
						else if(isNumericType(cell)){
							userTypeString = String.valueOf(Math.round(cell.getNumericCellValue()));
						}
						else if(isBooleanType(cell)){
							userTypeString = String.valueOf(cell.getBooleanCellValue());
						}
						else{
							userTypeString = cell.getRichStringCellValue().getString().trim();
						}
						userInfo1.setRoleId(Long.parseLong(userTypeString));
						break;
					
				}
			}
			if(userInfo1.getFirstName() == null || "".equals(userInfo1.getFirstName().trim())){
				outputRow.createCell(6).setCellValue(new HSSFRichTextString("Fail: First Name is mandatory"));
				return;
			}
			else if(userInfo1.getLastName() == null || "".equals(userInfo1.getLastName().trim())){
				outputRow.createCell(6).setCellValue(new HSSFRichTextString("Fail: Last Name is mandatory"));
				return;
			}
			else if(userInfo1.getUsername() == null || "".equals(userInfo1.getUsername().trim())){
				outputRow.createCell(6).setCellValue(new HSSFRichTextString("Fail: User Name is mandatory"));
				return;
			}
			else if(userInfo1.getPassword() == null || "".equals(userInfo1.getPassword().trim())){
				outputRow.createCell(6).setCellValue(new HSSFRichTextString("Fail: Password is mandatory"));
				return;
			}
			else if(userInfo1.getExamTypeId() == null ){
				outputRow.createCell(6).setCellValue(new HSSFRichTextString("Fail: Exam ID is mandatory"));
				return;
			}
			else if(userInfo1.getRoleId() == null ){
				outputRow.createCell(6).setCellValue(new HSSFRichTextString("Fail: User ID is mandatory"));
				return;
			}			
			else{
				//Collections.sort(answers,new AnswerCompartor());
				userInfoService.create(userInfo1);
				return;				
			}
		}
		catch(ServiceBeanException sbe){
			outputRow.createCell(6).setCellValue(new HSSFRichTextString(sbe.getMessage()));
			return;
		}
	}
	
	/**
	 * This method creates the file format.
	 * @return
	 */
	private HSSFWorkbook createBasicUserFile(){
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet();
		HSSFRow row = sheet.createRow(0);
		row.createCell(0).setCellValue(new HSSFRichTextString("First Name"));
		row.createCell(1).setCellValue(new HSSFRichTextString("Last Name"));
		row.createCell(2).setCellValue(new HSSFRichTextString("User Name"));
		row.createCell(3).setCellValue(new HSSFRichTextString("Password"));
		row.createCell(4).setCellValue(new HSSFRichTextString("Exam ID"));
		row.createCell(5).setCellValue(new HSSFRichTextString("User Type"));
		row.createCell(6).setCellValue(new HSSFRichTextString("Result"));
		return workbook;
	}
	public ActionForward isUserNameExist(ActionMapping mapping,UserForm userForm,HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		try{
			UserInfoServiceDelegate userService = new UserInfoServiceDelegate();
			SearchVO searchVO = new SearchVO();
			searchVO.addEqualsCondition("username", userForm.getUser_name());
			
			List<UserInfo> userList = userService.searchUser(searchVO);
			if(userList!= null && userList.size()>0){
				response.getWriter().write("TRUE");
			}else{
				response.getWriter().write("");
			}
		}
		catch(ServiceBeanException sbe){
			logger.error(sbe);			
		}
		catch(DelegateException de){
			logger.error(de);			
		}		
		return null;		
	}
	
	public ActionForward updateUser(ActionMapping mapping,UserForm loc_o_form, HttpServletRequest request,
		HttpServletResponse response) throws IOException, ServletException{
	    try{
	    	ActionMessages errors  = new ActionMessages() ;
	    	HttpSession loc_o_session = request.getSession();
			UserInfo tUserInfo = (UserInfo)loc_o_session.getAttribute(LoginConstants.SESSION_USER_INFO);
			UserInfoServiceDelegate userInfoService = new UserInfoServiceDelegate();
			Long userID = Long.parseLong(loc_o_form.getUser_id());
	    	UserInfo userInfo= userInfoService.read(userID);
	    	Long examTypeId = Long.parseLong(loc_o_form.getExam_type());
    		userInfo.setFirstName(loc_o_form.getFirst_name());
    		userInfo.setLastName(loc_o_form.getLast_name());
    		userInfo.setStatus(new Short(loc_o_form.getStatus()));
    		userInfo.setExamTypeId(examTypeId);
    		userInfo.setModifiedOn(new Date());
    		userInfo.setModifiedBy(tUserInfo.getUsername());
    		userInfo = userInfoService.update(userInfo);
    		if(userInfo != null){
    			List<UserRole> userRoleList = userInfoService.getUserRoleList(userInfo.getId());
    			loc_o_form.setUser_type(userRoleList.get(0).getId().getUserRoleTypeId().toString());
				if (userRoleList.get(0).getId().getUserRoleTypeId()== LoginConstants.USER_EXAMINEE){
		    		loc_o_form.setExam_type(userInfo.getExamTypeId().toString());
		    		ExaminationServiceDelegate examinationService = new ExaminationServiceDelegate();
			    	loc_o_form.setExam_type_list(examinationService.fetchActiveExams());
		    	}
				else{
					loc_o_form.setExam_type("");
				}
		    	ActionMessages messages = new ActionMessages();
		    	messages = new ActionMessages();
	            messages.add("result", new ActionMessage("user.updated.successfully"));
	            saveMessages(request, messages);
	            loc_o_form.setScreen_type("View");
    		}
    		else{
				errors.add("error", new ActionMessage("Exam.update.fail"));
				loc_o_form.setScreen_type("Edit");
			}
    		saveErrors(request, errors);
    		return mapping.findForward("success");
		}
		catch (Exception e){
			logger.error(e, e);
			return mapping.findForward("error");
		}
	}
	
	public ActionForward userSearchdetail(ActionMapping mapping,UserForm loc_o_form, HttpServletRequest request ) 
		throws IOException, ServletException{
	    try{
	    	UserInfoServiceDelegate userInfoService = new UserInfoServiceDelegate();
	    	UserRolePermissionServiceDelgate userRolePermissionService = new UserRolePermissionServiceDelgate();
	    	Long userID = Long.parseLong(loc_o_form.getUser_id());
	    	UserInfo userInfo= userInfoService.read(userID);
	    	loc_o_form.setUser_name(userInfo.getUsername());
	    	loc_o_form.setFirst_name(userInfo.getFirstName());
	    	loc_o_form.setLast_name(userInfo.getLastName());	    	
	    	loc_o_form.setStatus(String.valueOf(userInfo.getStatus()));
	    	List<UserRole> userRoleList = userInfoService.getUserRoleList(userInfo.getId());
	    	loc_o_form.setUser_type(userRoleList.get(0).getId().getUserRoleTypeId().toString());
			if (userRoleList.get(0).getId().getUserRoleTypeId()== LoginConstants.USER_EXAMINEE){
	    		loc_o_form.setExam_type(userInfo.getExamTypeId().toString());
	    		ExaminationServiceDelegate examinationService = new ExaminationServiceDelegate();
		    	loc_o_form.setExam_type_list(examinationService.fetchActiveExams());
	    	}
			else{
				loc_o_form.setExam_type("");
			}
	    	/* Set the List of role list in drop down as per the logged in User's Role */
	    	HttpSession session = request.getSession();
	    	HashMap permissionMap = ((HashMap)(session.getAttribute(LoginConstants.SESSION_USER_PERMISSION_INFO)));
	    	/* Check Authentication for user EDIT*/
	    	List<UserPermissionType> permissionList = userRolePermissionService.getPermissionListByUserId(userInfo.getId());
	    	boolean isAuthenticatedForEdit  = isAuthenticatedForEdit(permissionList,permissionMap);
	    	
	    	if(isAuthenticatedForEdit){
		    	return mapping.findForward("success");
	    	}
	    	else{
	    		ActionMessages messages = new ActionMessages();
	    		messages.add("error", new ActionMessage("user.edit.unauthentic",userInfo.getUsername()));
	    		saveMessages(request, messages);	    		
		    	return mapping.findForward("unauthencatedForEditingUser");
	    	}
	    }
	    catch(Exception e){
	    	logger.error(e, e);
	    	return mapping.findForward("error");
	    }
	 }
	
	private boolean isAuthenticatedForEdit( List<UserPermissionType> rolePermissionList, HashMap permissionMap) {
		String permissionName = "";
		boolean isAuthenticated = true;
		for(int j=0;j<rolePermissionList.size();j++) {
			permissionName = (rolePermissionList.get(j).getName());
			if(permissionMap.get(permissionName) == null){
				isAuthenticated = false;
				break ;
			}			
		}
		return isAuthenticated;		
	}	
   
	public ActionForward searchUserResult(ActionMapping mapping,UserForm loc_o_form) 
		throws IOException, ServletException{
	    try{
	    	UserInfoServiceDelegate userInfoService = new UserInfoServiceDelegate();
	    	SearchVO searchVO = new SearchVO();
	    	if(loc_o_form.getUser_name() != null && !"".equals(loc_o_form.getUser_name().trim())){
	    		searchVO.addLikeCondition("username", loc_o_form.getUser_name());
	    	}
	    	if(loc_o_form.getFirst_name() != null && !"".equals(loc_o_form.getFirst_name().trim())){
	    		searchVO.addLikeCondition("firstName", loc_o_form.getFirst_name());
	    	}
	    	if(loc_o_form.getLast_name() != null && !"".equals(loc_o_form.getLast_name().trim())){
	    		searchVO.addLikeCondition("lastName", loc_o_form.getLast_name());
	    	}
	    	if(loc_o_form.getUser_type() != null && !"".equals(loc_o_form.getUser_type().trim())){
	    		if("1".equals(loc_o_form.getUser_type().trim())){
	    			searchVO.addIsNullCondition("examTypeId");
	    		}
	    		else{
	    			searchVO.addIsNotNullCondition("examTypeId");
	    		}
	    	}
	    	if(loc_o_form.getScreen_type().equals("Edit")){
	    		searchVO.addEqualsCondition("status", LoginConstants.USER_ACTIVE);
	    	}
	    	searchVO.addNotEqualsCondition("username", "system");
	    	List<UserInfo> userInfoList =  userInfoService.searchUser(searchVO);
	    	loc_o_form.setShow_list("Y");
    		loc_o_form.setUser_list(userInfoList);    		
	    	return mapping.findForward("success");
	    }
	    catch(Exception e){
	    	logger.error(e, e);
	    	return mapping.findForward("error");
	    }
	 }

	public ActionForward searchUserScreen(ActionMapping mapping,UserForm loc_o_form) 
		throws IOException, ServletException{
		try{
			if(loc_o_form.getShow_list() == null || loc_o_form.getShow_list().equals("")){
				loc_o_form.setShow_list("N");
			}
			return mapping.findForward("success");
	    }
		catch (Exception e){
			logger.error(e, e);
			return mapping.findForward("error");
		 }
	}

	public ActionForward createEditUserScreen(ActionMapping mapping,UserForm loc_o_form,HttpServletRequest request)
		throws IOException, ServletException{
	    try{
	    	resetForm(loc_o_form);
	    	ExaminationServiceDelegate examinationService = new ExaminationServiceDelegate();
	    	loc_o_form.setExam_type_list(examinationService.fetchActiveExams());
	    	return mapping.findForward("success");
		}
		catch (Exception e){
			logger.error(e, e);
			return mapping.findForward("error");
		}
	}
	
	public ActionForward addUser(ActionMapping mapping,UserForm loc_o_form, HttpServletRequest request,HttpServletResponse response) 
		throws IOException, ServletException{
		boolean isUserExist = false;
	    try{
	    	HttpSession loc_o_session = request.getSession();
			UserInfo tUserInfo = (UserInfo)loc_o_session.getAttribute(LoginConstants.SESSION_USER_INFO);
			UserInfoServiceDelegate userInfoService = new UserInfoServiceDelegate();
	    	UserInfo userInfo= null;
	    	List<UserInfo> userInfoList = new ArrayList<UserInfo>();
	    	Long examTypeId = null;
	    	Long roleId = Long.parseLong(loc_o_form.getUser_type());
	    	
	    	if(loc_o_form.getExam_type() != null){
	    		try{
	    			examTypeId = Long.parseLong(loc_o_form.getExam_type());
	    		}catch(Exception e){
	    			logger.error(e);
	    		}
	    	}
	    	Date createdOn = new Date();
	    	for(int i =0;i<loc_o_form.getUser_name_array().length;i++){
	    		userInfo = new UserInfo();
	    		userInfo.setUsername(loc_o_form.getUser_name_array()[i]);
	    		userInfo.setPassword(userInfoService.encryptPassword(loc_o_form.getPassword_array()[i]));
	    		userInfo.setRetryPasswordCount((byte)3);
	    		userInfo.setFirstName(loc_o_form.getFirst_name_array()[i]);
	    		userInfo.setLastName(loc_o_form.getLast_name_array()[i]);
	    		userInfo.setIsDefault(true);
	    		userInfo.setStatus(LoginConstants.USER_ACTIVE);
	    		userInfo.setExamTypeId(examTypeId);
	    		userInfo.setRoleId(roleId);
	    		userInfo.setCreatedBy(tUserInfo.getUsername());
	    		userInfo.setCreatedOn(createdOn);
	    		userInfoList.add(userInfo);
	    	}
	    	userInfoList = userInfoService.create(userInfoList);
	    	HSSFWorkbook outputFile = createBasicRedemptionFile();
			HSSFSheet outputSheet = outputFile.getSheetAt(0);
			int rowIndex = 1,passwordIndex=0;
			for(UserInfo userInfoTemp:userInfoList){
				HSSFRow outputRow = outputSheet.createRow(rowIndex++);
				outputRow.createCell(0).setCellValue(userInfoTemp.getFirstName());
				outputRow.createCell(1).setCellValue(userInfoTemp.getLastName());
				outputRow.createCell(2).setCellValue(userInfoTemp.getUsername());
				outputRow.createCell(3).setCellValue(loc_o_form.getPassword_array()[passwordIndex++]);
			}
			File file = null;
			File fileTemp = null;
			DataOutputStream dos = null;
			FileOutputStream fos;
			SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy-hh-mm-ss"); 
			if(examTypeId != null){
				ExaminationServiceDelegate examService = new ExaminationServiceDelegate();
				ExamType examType = examService.getExam(examTypeId);
				fileTemp= new File("D:/ProductionFiles/Examinee");
				fileTemp.mkdir();
				file = new File("D:/ProductionFiles/Examinee/"+examType.getName()+"-"+sdf.format(new Date())+".xls");
			}else{
				fileTemp= new File("D:/ProductionFiles/Examiner");
				fileTemp.mkdirs();
				file = new File("D:/ProductionFiles/Examiner/"+sdf.format(new Date())+".xls");				
			}			
			file.createNewFile();
			fos = new FileOutputStream(file);
			dos=new DataOutputStream(fos);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			outputFile.write(bos);
			dos.write(bos.toByteArray());			
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition","attachment; filename=Users File");
			ServletOutputStream outputStream = response.getOutputStream();
			outputStream.write(bos.toByteArray());
			outputStream.flush();
			outputStream.close();
			dos.close();
			fos.close();
	    	ActionMessages messages = new ActionMessages();
	    	if(isUserExist){
	    		messages.add("error", new ActionMessage("username.exist"));
	    		saveErrors(request, messages);
	    	}
	    	else{
		    	resetForm(loc_o_form);
		    	messages = new ActionMessages();
	            messages.add("result", new ActionMessage("user.added.successfully"));
	            saveMessages(request, messages);
	    	}
	    	return null;
		}
		catch (Exception e){
			logger.error(e, e);
			return mapping.findForward("error");
		}
	}
	
	public void resetForm(UserForm loc_o_form){
        loc_o_form.setUser_name("");
        loc_o_form.setFirst_name("");
        loc_o_form.setLast_name("");
        loc_o_form.setUser_type("");
	}
	
	private HSSFWorkbook createBasicRedemptionFile(){
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet("Without Database Error");
		HSSFRow row = sheet.createRow(0);
		row.createCell(0).setCellValue(new HSSFRichTextString("First Name"));
		row.createCell(1).setCellValue(new HSSFRichTextString("Last Name"));
		row.createCell(2).setCellValue(new HSSFRichTextString("User Name"));
		row.createCell(3).setCellValue(new HSSFRichTextString("Password"));	
		row.createCell(4).setCellValue(new HSSFRichTextString("Exam ID"));	
		row.createCell(5).setCellValue(new HSSFRichTextString("User Type"));	
		return workbook;
	}
	private  boolean isNumericType(HSSFCell cell){
		return HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType() && !HSSFDateUtil.isCellDateFormatted(cell);
	}
	 
	private  boolean isDateType(HSSFCell cell){
		return HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType() && HSSFDateUtil.isCellDateFormatted(cell);
	}
	private  boolean isBooleanType(HSSFCell cell){
		return HSSFCell.CELL_TYPE_BOOLEAN == cell.getCellType();
	}
}
